/*************************************************************************
	> File Name: week15-sharememory.c
	> Author: ma6174
	> Mail: ma6174@163.com 
	> Created Time: 2014年06月11日 星期三 22时35分11秒
 ************************************************************************/

#include <stdio.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdlib.h>

int main(int argc, char * argv[]) {
    int shmid;
    int pid;
    const char * childsay = "Hi, this is child process sending message!";
    char * shmaddr = NULL;
    struct shmid_ds * buf = (struct shmid_ds *)malloc(sizeof(struct shmid_ds));

    while ((shmid = shmget(IPC_PRIVATE, 1000, IPC_CREAT|0600)) == -1) {
        perror("Shmget");
    }

    while((pid = fork()) == -1) {
        perror("Fork");
    }

    if(pid == 0) {
        fprintf(stdout, "This is child process(pid= %d)\n", getpid());
        // Attach
        shmaddr = (char *)shmat(shmid, NULL, 0);
        
        strcpy(shmaddr, childsay);
        printf("%s\n", shmaddr);
        shmdt(shmaddr);
        exit(0);
    } else {
        wait(0);
        fprintf(stdout, "This is parent process(pdi = %d)\n", getpid());
        // 
        shmctl(shmid, IPC_STAT, buf);
        fprintf(stdout, "Shm_segsz:%d\nChm_cpid:%d\nShm_lpid=%d\n", buf->shm_segsz,buf->shm_cpid, buf->shm_lpid);
        shmaddr = (char *)shmat(shmid, NULL, 0);
        fprintf(stdout, "Child Response: %s\n", shmaddr);
        shmdt(shmaddr);
        shmctl(shmid, IPC_RMID, NULL);
    }

    free(buf);

    return 0;
}
